/**
 * 
 */
package com.et114.modules.products.params;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.et114.components.acegi.Constants;
import com.et114.components.simpletable.DataList;
import com.et114.core.action.BaseDispatchAction;
import com.et114.core.common.AppContext;
import com.et114.core.common.CONST;
import com.et114.core.utility.ArgumentTokenizer;
import com.et114.core.utility.NumberUtils;
import com.et114.core.utility.StringPool;
import com.et114.modules.products.commons.Const;
import com.et114.modules.products.commons.PorJsonObj;
import com.et114.modules.products.services.ProPropertySetImp;
import com.et114.modules.products.vo.PropertyData;
import com.et114.modules.system.dictionary.DictionaryCache;
import com.et114.modules.system.dictionary.vo.BizOption;
import com.et114.components.xmlparse.XMLUtils; 

import com.opensymphony.module.propertyset.PropertySet;

/*
 * @author guanhw
 */
public class ParamTypeAction extends BaseDispatchAction {
	
	@ SuppressWarnings ( "unchecked" )
	public  ActionForward getParamType( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception {
		//DIC
		List< BizOption > dicOps = DictionaryCache.getInstance ( ).listBizOptions( Const.DIC_PRO_TYPE_KEY ,  true  , CONST.COUNTRY_ZH  ) ;
		request.setAttribute ( "dicOps" , dicOps ) ;
		List< BizOption > csOps = DictionaryCache.getInstance ( ).listBizOptions( Const.DIC_COMMON_STATUS_KEY ,  true  , CONST.COUNTRY_ZH  ) ;
		request.setAttribute ( "csOps" , csOps ) ;
		List< BizOption > chsOps = DictionaryCache.getInstance ( ).listBizOptions( Const.DIC_COMMON_HTML_SELECT ,  true  , CONST.COUNTRY_ZH  ) ;
		request.setAttribute ( "chsOps" , chsOps ) ;
	
		
		//PARAMS
		ParamTypeForm typeForm = ( ParamTypeForm ) form ; 
		Long typeId = typeForm.getTypeId ( ) ; 
		
		ParamType vo = new ParamType( ) ;
		PropertyUtils.copyProperties ( vo , typeForm ) ; 
		
		//BIS
		ParamServiceImpl psi = ( ParamServiceImpl )getBean( "paramServiceImpl" ) ; 
		if (  !NumberUtils.isEmptyOrZero ( typeId ) ) { //load one
			vo = psi.getParamTypeById ( typeId ) ; 
			request.setAttribute ( "vo" , vo ) ; 
			return mapping.findForward ( "editparamTypes" ) ; 
		}
		else { // loads
			DataList dl = psi.getParamTypes ( vo ) ; 
			request.setAttribute ( "dl" , dl ) ; 
			request.setAttribute ( "searchvo" , vo ) ;
			return mapping.findForward ( "paramTypes" ) ;
		}
	}
	
	@ SuppressWarnings ( "unchecked" )
	public  ActionForward toEditParamType( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception {
		List < BizOption > dicOps = DictionaryCache.getInstance ( )
				.listBizOptions ( Const.DIC_PRO_TYPE_KEY , false ,
						CONST.COUNTRY_ZH );
		request.setAttribute ( "dicOps" , dicOps );
		List < BizOption > chsOps = DictionaryCache.getInstance ( )
				.listBizOptions ( Const.DIC_COMMON_HTML_SELECT , false ,
						CONST.COUNTRY_ZH );
		request.setAttribute ( "chsOps" , chsOps );
		List < BizOption > csOps = DictionaryCache.getInstance ( )
				.listBizOptions ( Const.DIC_COMMON_STATUS_KEY , false ,
						CONST.COUNTRY_ZH );
		request.setAttribute ( "csOps" , csOps );
		
		
		//PARAMS
		ParamTypeForm typeForm = ( ParamTypeForm ) form ; 
		ParamType vo = new ParamType( ) ;
		PropertyUtils.copyProperties ( vo , typeForm ) ; 
		
		ParamServiceImpl psi = ( ParamServiceImpl )getBean( "paramServiceImpl" ) ; 		
		Long parentId = typeForm.getParentId ( ) ; 
		if ( parentId != null && parentId != 0L ) {
			vo.setParent (  psi.getParamTypeById ( parentId ) ) ; 
		}
		
		
		request.setAttribute ( "vo" , vo ) ; 
		return mapping.findForward ( "editparamTypes" ) ;
	}
	
	
	public  ActionForward editParamType( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception {
		//DIC
		
		//PARAMS
		ParamTypeForm typeForm = ( ParamTypeForm ) form ; 
		Long typeId = typeForm.getTypeId ( ) ; 
		Long parentId = typeForm.getParentId ( ) ;
		ParamType vo = new ParamType( ) ;
		PropertyUtils.copyProperties ( vo , typeForm ) ; 
		
		
		//BIS
		ParamServiceImpl psi = ( ParamServiceImpl )getBean( "paramServiceImpl" ) ; 
		if (  !NumberUtils.isEmptyOrZero ( typeId ) ) {  //update
			psi.updateParamType ( vo ) ; 
		}
		else { //save
			typeId = psi.saveParamType ( vo ) ; 
		}
		
		
		return new ActionForward (
				"paramtype.go?method=getParamType&flg=1&typeId=" + typeId
						+ "&parentId=" + parentId , true );
	}
	
	
	public  ActionForward removeParamType( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception {
		//DIC
		
		//PARAMS
		//
		ParamServiceImpl psi = ( ParamServiceImpl )getBean( "paramServiceImpl" ) ; 
		
		ParamTypeForm typeForm = ( ParamTypeForm ) form ; 
		String globalKey = typeForm.getGlobalKey ( ) ; 
		Long parentId = typeForm.getParentId ( ) ; 
		
		Long[] deleteIds = typeForm.getDeleteId ( ) ; 
		//ParamType vo = null ; 
		if ( deleteIds != null  ) {
			for ( Long deleteId : deleteIds  ) {
				psi.removeParamType ( deleteId ) ;
				//psi.removeParamType ( deleteId ) ; 
//				vo = psi.getParamTypeById ( deleteId ) ; 
//				if ( vo != null  ) {
//					if (  !NumberUtils.isEmptyOrZero ( parentId ) ) {
//						
//					}
//					
					//vo.setRemoveMark ( String.valueOf ( Const.COMMON_REMOVE_MARK_Y ) ) ; 
					//psi.updateParamType ( vo ) ;
					
//				}
			}
		}
		
		String to = "paramtype.go?method=getParamType&flg=1&globalKey=" + globalKey ; 
		//if ( !NumberUtils.isEmptyOrZero( parentId ) ) {
			to += "&parentId=" + parentId ;
		//}
			
		return new ActionForward ( to 
				 , true );
	}
	
	
	
	//GENERATE FORM PARAM //TODO CACHE
	@ SuppressWarnings ( "unchecked" )
	public  ActionForward generateParamForm( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception {
		long ct = System.currentTimeMillis ( ) ; 
		//DIC
		
		//PARAMS
		ParamTypeForm typeForm = ( ParamTypeForm ) form ; 
		Long proId = typeForm.getProId ( ) ; 
		String globalKey = typeForm.getGlobalKey ( ) ; 
		if ( StringUtils.isEmpty ( globalKey ) || StringUtils.isBlank ( globalKey ) 
				|| NumberUtils.isEmptyOrZero ( proId ) ) 		
			throw new Exception( Constants.SYS_EXP_K + "GlobalKey is Null !" ) ; 
		
		ParamType vo = new ParamType () ; 
		
		PropertyUtils.copyProperties ( vo , typeForm ) ; 

		//BIS
		ParamServiceImpl psi = ( ParamServiceImpl )getBean( "paramServiceImpl" ) ; 
		vo.setWorkflg ( Const.COMMON_STATUS_ENA ) ; 
		 
		List< ParamType > paramTypesTmp = new ArrayList( ) ; //psi.getParamTypeList (  vo ) ; 		
	
		List< ParamType > paramTypeRoots = psi.getRootParamType( vo ) ;
		for ( ParamType paramType : paramTypeRoots ) {
			if ( paramType.getWorkflg ( ) == Const.COMMON_STATUS_ENA )
				paramTypesTmp.addAll ( paramType.getChilds ( ) ) ;
		}
		
		
		
		ProPropertySetImp proPropertySetImp = ( ProPropertySetImp )getBean ( "proPropertySetImp" ) ; 
		proPropertySetImp.setGlobalKey ( globalKey + StringPool.DASH + proId ) ;
		List< PropertyData > keys = ( List )proPropertySetImp.getKeys ( null ) ; 
		
		
		Map< String , String  > keyMap = new HashMap< String , String  >(  ) ; 
		if ( keys != null )
			for ( PropertyData propertyData : keys ) {
				keyMap.put ( propertyData.getItemKey ( ) , propertyData.getStringValue ( ) ) ; 
			}
		
		
		Map< String , String > values = new HashMap< String , String >( ) ;
		
		
		logger.info ( "generate form time-1:" + ( System.currentTimeMillis ( ) - ct ) ) ; 
		
		String in = "";
		
		if (  paramTypesTmp != null ) {
			for ( ParamType paramType : paramTypesTmp ) {
				in = in + paramType.getTypeId ( ) ;
				if ( Const.COMMON_HTML_SELECT_M == paramType.getShowStyle ( ) || 
					 Const.COMMON_HTML_SELECT_S == paramType.getShowStyle ( ) || 
					 Const.COMMON_HTML_SELECT_T == paramType.getShowStyle ( ) ) { //more
					List < ParamValue > paramValues = paramType.getParamValues ( );
					for ( ParamValue paramValue : paramValues ) {
						Long paramId = paramValue.getParamId ( ) ; 
						String paramKey = in + StringPool.DASH + paramId ;
						if ( keyMap.containsKey ( paramKey ) ) {
							values.put ( paramKey , keyMap.get ( paramKey ) ) ;
							
						}
					}

				}
			
				in =  "";
			}			
		}

	

		
		request.setAttribute ( "proId" , proId ) ; 
		request.setAttribute ( "vo" , vo ) ;
		request.setAttribute ( "keys" , keys ) ;
		request.setAttribute ( "paramTypes" , paramTypeRoots ) ;
		request.setAttribute ( "values" , values ) ;
		
		logger.info ( "generate form time:" + ( System.currentTimeMillis ( ) - ct ) ) ;
		return mapping.findForward ( "paramsform" ) ; 
	}
	
	@ SuppressWarnings ( "unchecked" )
	public  ActionForward editParamForm( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception {
		//DIC
		
		//PARAMS
		ParamTypeForm typeForm = ( ParamTypeForm ) form ; 
		String params = typeForm.getParams ( ) ;
		Long proId = typeForm.getProId ( ) ; 
		String globalKey = typeForm.getGlobalKey ( ) ; 
		if ( StringUtils.isEmpty ( globalKey ) || StringUtils.isBlank ( globalKey ) 
				|| NumberUtils.isEmptyOrZero ( proId ) ) 		
			throw new Exception( Constants.SYS_EXP_K + "GlobalKey is Null !" ) ; 
		
		ParamType vo = new ParamType () ; 
		PropertyUtils.copyProperties ( vo , typeForm ) ; 
		
		ProPropertySetImp proPropertySetImp = ( ProPropertySetImp )getBean ( "proPropertySetImp" ) ; 
		proPropertySetImp.setGlobalKey ( globalKey + StringPool.DASH + proId ) ;
		
		List tmp = new ArrayList( ) ; 
		
		List< PropertyData > keys = ( List )proPropertySetImp.getKeys ( null ) ; 
		Map< String , String  > keyMap = new HashMap< String , String  >(  ) ; 
		if ( keys != null )
			for ( PropertyData propertyData : keys ) {
				keyMap.put ( propertyData.getItemKey ( ) , propertyData.getStringValue ( ) ) ; 
			}
		
		PropertyData propertyData = null ; 
		if ( !StringUtils.isEmpty ( params ) && !StringUtils.isBlank ( params )  ) {
			ArgumentTokenizer ats = new ArgumentTokenizer( params , ';' ) ; 
			while (  ats.hasNext ( ) ) {
				String ass = ats.next ( ) ; 
				ArgumentTokenizer as = new ArgumentTokenizer( ass , ':' ) ;
				while( as.hasNext ( ) ) {
					String key = as.next ( ) ; 
					String value = as.next ( ) ; 
						if ( keyMap.containsKey ( key ) ||  !keyMap.containsKey ( key )) {
							if ( !value.equals (  keyMap.get ( key ) ) ) {
								proPropertySetImp.setImpl ( PropertySet.STRING , key ,  value  ) ;
							}
							tmp.add ( key ) ;
						}
				}
			}
		}
		
		
		for ( java.util.Iterator <  PropertyData > iter = keys.iterator ( ) ; iter.hasNext ( ) ;  ) {
			propertyData = iter.next ( ) ; 
			if ( !tmp.contains ( propertyData.getItemKey ( ) ) ) 
				proPropertySetImp.remove ( propertyData.getItemKey ( ) ) ;
		}
		
		return new ActionForward (
				"paramtype.go?method=generateParamForm&globalKey=" + globalKey
						+ "&proId=" + proId , true );
	}
	
	
	public  ActionForward toDisOrderParamType( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception {
		//DIC
		
		//PARAMS
		ParamTypeForm typeForm = ( ParamTypeForm ) form ; 
		String globalKey = typeForm.getGlobalKey ( ) ; 
		if ( StringUtils.isEmpty ( globalKey ) || StringUtils.isBlank ( globalKey ) )   {
			throw new Exception( "globalKey is NULL !" ) ; 
		}
		
		//PARAMS
		
		ParamType vo = new ParamType( ) ;
		PropertyUtils.copyProperties ( vo , typeForm ) ; 
		
		//BIS
		ParamServiceImpl psi = ( ParamServiceImpl )getBean( "paramServiceImpl" ) ; 

		List< ParamType > paramTypes = psi.getParamTypeList ( vo ) ; 
		request.setAttribute ( "paramTypes" , paramTypes ) ;
		request.setAttribute ( "vo" , vo ) ; 
		return mapping.findForward ( "toDisOrderParamType" ) ; 
	}
	
	
	
	
	
	public  ActionForward orderParamType( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception {
		//DIC
		
		//PARAMS
		ParamTypeForm typeForm = ( ParamTypeForm ) form ; 
		Long parentId = typeForm.getParentId ( ) ; 
		String globalKey = typeForm.getGlobalKey ( ) ; 
		if ( StringUtils.isEmpty ( globalKey ) || StringUtils.isBlank ( globalKey ) )   
			throw new Exception( "globalKey is NULL !" ) ; 
		
		
		//PARAMS
		String orders = typeForm.getOrders ( ) ; 
		
		//BIS
		ParamServiceImpl psi = ( ParamServiceImpl )getBean( "paramServiceImpl" ) ; 
		if ( orders != null  ) {
			StringTokenizer st = new StringTokenizer( orders , StringPool.SEMICOLON ) ;
			int count = st.countTokens ( ) ; 
			ParamType paramType = null ; 
			for (  int i = 0 ; i <  count ; i ++ ) {
				Long orderId = Long.valueOf ( st.nextToken() );
				paramType = psi.getParamTypeById ( orderId ) ; 
				paramType.setDisplOrder ( Long.valueOf ( i + 1 ) ) ;
				psi.updateParamType ( paramType ) ;
			}
		}
		
			
		
		String to = "paramtype.go?method=toDisOrderParamType&globalKey="
			+ globalKey  ; 
		
		//if ( !NumberUtils.isEmptyOrZero( parentId ) )
			to += "&parentId=" + parentId ;
		
		return new ActionForward (	to , true );
	}	
	
	public  ActionForward generateParamTypeTree( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception {
		response.setContentType ( "text/xml;charset="
				+ AppContext.getFrameWorkPropertiesBean ( ).getCharSet ( ) );

		//DIC
		
		//PARAMS
		ParamTypeForm typeForm = ( ParamTypeForm ) form ; 
		String globalKey = typeForm.getGlobalKey ( ) ; 
		if ( StringUtils.isEmpty ( globalKey ) || StringUtils.isBlank ( globalKey ) )   
			throw new Exception( "globalKey is NULL !" ) ; 
		
		ParamType vo = new ParamType( ) ;
		PropertyUtils.copyProperties ( vo , typeForm ) ; 

		ParamServiceImpl psi = ( ParamServiceImpl )getBean( "paramServiceImpl" ) ; 
		
		List< ParamType > roots = psi.getRootParamType (  vo ) ; 
		
		
		StringBuffer sb = new StringBuffer ( );
		sb.append("<?xml version=\"1.0\" encoding=\"" + AppContext.getFrameWorkPropertiesBean ( ).getCharSet ( ) + "\"?>");

		sb.append ( "<tree id=\"0\"><item text=\"参数类型树\" id=\"-1\" open=\"1\" >" )
				.append ( "\n" );
		for ( ParamType root : roots )  {
			String tn = root.getTypeName ( ) ; 
			if ( tn != null )
				tn = XMLUtils.writeEscapedXml( tn.toCharArray ( ) ) ; 
			sb.append ( "<item text=\"" +  tn   + "\" id=\""
							+ root.getTypeId ( ) + "\" />" ).append ( "\n" );
		}
		sb.append ( "</item></tree> " );
		

		response.getWriter ( ).print (  sb );
		response.getWriter ( ).flush ( );
		response.getWriter ( ).close ( );
		return null;
		
	}
	
	public  ActionForward paramIndex( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception {
		//DIC
		
		//PARAMS
		ParamTypeForm typeForm = ( ParamTypeForm ) form ; 
		String globalKey = typeForm.getGlobalKey ( ) ; 
		if ( StringUtils.isEmpty ( globalKey ) || StringUtils.isBlank ( globalKey ) )   
			throw new Exception( "globalKey is NULL !" ) ; 
		
		ParamType vo = new ParamType( ) ;
		PropertyUtils.copyProperties ( vo , typeForm ) ; 

		
		request.setAttribute ( "vo" , vo ) ; 
		return mapping.findForward ( "paramIndex" ) ;
	}
	
	public  ActionForward paramManager( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception {
		//DIC
		
		//PARAMS
		ParamTypeForm typeForm = ( ParamTypeForm ) form ; 
		String globalKey = typeForm.getGlobalKey ( ) ; 
		if ( StringUtils.isEmpty ( globalKey ) || StringUtils.isBlank ( globalKey ) )   
			throw new Exception( "globalKey is NULL !" ) ; 
		
		ParamType vo = new ParamType( ) ;
		PropertyUtils.copyProperties ( vo , typeForm ) ; 

		
		request.setAttribute ( "vo" , vo ) ; 
		return mapping.findForward ( "paramsManager" ) ;
	}	
	
	
	//高级查询

	public  ActionForward generateAdvParamForm( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception {
		long ct = System.currentTimeMillis ( ) ; 
		//DIC
		
		//PARAMS
		ParamTypeForm typeForm = ( ParamTypeForm ) form ; 
		String globalKey = typeForm.getGlobalKey ( ) ; 
		String to = typeForm.getForwardTo ( ) ; 
		if ( StringUtils.isEmpty ( globalKey ) || StringUtils.isEmpty ( to )
				|| StringUtils.isBlank ( globalKey )
				)
			throw new Exception ( Constants.SYS_EXP_K + "GlobalKey is Null !" );

		ParamType vo = new ParamType () ; 
		
		PropertyUtils.copyProperties ( vo , typeForm ) ; 

		//BIS
		ParamServiceImpl psi = ( ParamServiceImpl )getBean( "paramServiceImpl" ) ; 
		vo.setWorkflg ( Const.COMMON_STATUS_ENA ) ; 
		 
		List< ParamType > paramTypesTmp = new ArrayList< ParamType > ( ) ; //psi.getParamTypeList (  vo ) ; 		
	
		List< ParamType > paramTypeRoots = psi.getRootParamType( vo ) ;
		for ( ParamType paramType : paramTypeRoots ) {
			if ( paramType.getWorkflg ( ) == Const.COMMON_STATUS_ENA )
				paramTypesTmp.addAll ( paramType.getChilds ( ) ) ;
		}
		

		logger.info ( "generate generateAdvParamForm time-1:" + ( System.currentTimeMillis ( ) - ct ) ) ; 
		

		request.setAttribute ( "vo" , vo ) ;
		request.setAttribute ( "paramTypes" , paramTypeRoots ) ;
		
		logger.info ( "generate generateAdvParamForm time:" + ( System.currentTimeMillis ( ) - ct ) ) ;
		return mapping.findForward ( to ) ; 
	}
	
	
	/////4 q
	@ SuppressWarnings ( "unchecked" )
	public  ActionForward getParamInfo4View( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception {
		long ct = System.currentTimeMillis ( ) ; 
		response.setContentType ( "text/html;charset="
				+ AppContext.getFrameWorkPropertiesBean ( ).getCharSet ( ) );
		
		//DIC
		
		//PARAMS
		ParamTypeForm typeForm = ( ParamTypeForm ) form ; 
		String globalKey = typeForm.getGlobalKey ( ) ; 
		Long proId = typeForm.getProId ( ) ; 
		if ( StringUtils.isEmpty ( globalKey ) 
				|| StringUtils.isBlank ( globalKey ) || NumberUtils.isEmptyOrZero ( proId ) )
			return PorJsonObj.response ( response , PorJsonObj.error (
					CONST.COUNTRY_ZH ).toString ( ) ); 


		ParamType vo = new ParamType () ; 
		
		PropertyUtils.copyProperties ( vo , typeForm ) ; 

		//proset 
		ProPropertySetImp proPropertySetImp = ( ProPropertySetImp )getBean ( "proPropertySetImp" ) ; 
		proPropertySetImp.setGlobalKey ( globalKey + StringPool.DASH + proId ) ;
		List< PropertyData > keys = ( List )proPropertySetImp.getKeys ( null ) ; 
		
		
		Map< String , String  > keyMap = new HashMap< String , String  >(  ) ; 
		if ( keys != null )
			for ( PropertyData propertyData : keys ) {
				keyMap.put ( propertyData.getItemKey ( ) , propertyData.getStringValue ( ) ) ; 
			}
		
		//BIS
		ParamServiceImpl psi = ( ParamServiceImpl )getBean( "paramServiceImpl" ) ; 
		vo.setWorkflg ( Const.COMMON_STATUS_ENA ) ; 
		 	
		List< ParamType > paramTypeRoots = psi.getRootParamType( vo ) ;

		
		String jsonStr = PorJsonObj.getProParamsInfo( paramTypeRoots , keyMap , CONST.COUNTRY_ZH  ).toString ( ) ;
		logger.info ( "jsonStr:" + jsonStr ) ;
		logger.info ( "generate pro params info time-1:" + ( System.currentTimeMillis ( ) - ct ) ) ; 

		return PorJsonObj.response ( response , jsonStr );

	}
}
